package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.message.DefaultMessageFactory;
import sk.naive.talker.util.Utils;

import java.rmi.RemoteException;

/**
 *
 * @author <a href="mailto:richter@bgs.sk">Richard Richter</a>
 * @version $Revision: 1.23 $ $Date: 2005/01/25 21:57:04 $
 */
public abstract class AddressedMessageCommand extends AbstractMessageCommand {
	public final void exec()
		throws CommandException,
		RemoteException,
		PropertyStoreException
	{
		String recipientLogin = getRecipientLogin(user, params);
		String text = getMessage(params);
		if (!paramsCheck(recipientLogin, text)) {
			sendMisusageWarning();
			return;
		}
		User recipient = findTarget(recipientLogin);
		if (recipient == null) {
			return;
		}
		if (Utils.isIgnoring(recipient, getCategory())) {
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, recipient.getProperties());
			user.send(getString(ignoreWarning(), user.getProperties()));
			return;
		}
		if (additionalChecks()) {
			execSend(recipient, text);
		}
	}

	protected String getRecipientLogin(User user, String s) throws RemoteException {
		String[] sa = Utils.splitWords(s, 2);
		if (sa.length > 0) {
			return Utils.normalize(sa[0]);
		}
		return null;
	}

	protected String getMessage(String s) {
		String[] sa = Utils.splitWords(s, 2);
		if (sa.length > 1) {
			return sa[1];
		}
		return null;
	}

	protected abstract void execSend(User recipient, String text) throws RemoteException, CommandException, PropertyStoreException;

	protected boolean paramsCheck(String recipientLogin, String message) {
		return (recipientLogin != null && message != null);
	}

	protected boolean additionalChecks() {
		return true;
	}

	protected String ignoreWarning() {
		return "message.ignoreWarning";
	}

	protected String selfWarning() {
		return "message.selfWarning";
	}

	public abstract String getSenderMessageKey(String message);

	public abstract String getRecipientMessageKey(String message);
}
